package com.fintech.pangu.security.jwt.provider.authentication.token;

import com.fintech.pangu.commons.jwt.JWTUtil;
import com.fintech.pangu.security.authentication.token.AuthenticationToken;
import com.fintech.pangu.security.authentication.token.impl.DefaultAuthenticationToken;
import com.fintech.pangu.security.authentication.token.impl.DefaultAuthenticationTokenServices;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT认证令牌服务
 * 继承DefaultAuthenticationTokenServices默认实现，覆盖其具体的认证令牌生成逻辑
 */
@Setter
public class JwtAuthenticationTokenServices extends DefaultAuthenticationTokenServices {

    /**
     * jwt密匙
     */
    private String secret;

    /**
     * jwt过期时间(s)
     */
    private int jwtExpireInSeconds;


    @Override
    protected AuthenticationToken createAuthenticationTokenInner(Authentication authentication) {
        UserDetails userPrincipal = (UserDetails) authentication.getPrincipal();

        Map<String, Object> claims = new HashMap<>();
        String tokenValue = JWTUtil.generateToken(userPrincipal.getUsername(), secret, (jwtExpireInSeconds * 1000), claims);

        return new DefaultAuthenticationToken(tokenValue);
    }

}
